#include "dirsearch.h"
#include <QDir>
#include "exportxlsx.h"
#include <QDebug>
#include <synchapi.h>
#include <QThreadPool>
#include "exportrefm.h"

dirsearch::dirsearch()
{
    int role = Qt::UserRole;
    roleNames_.insert(role++, "number");
    roleNames_.insert(role++, "name");
    roleNames_.insert(role++, "checkTime");
    roleNames_.insert(role++, "checked");

    pool.setMaxThreadCount(1);
}

bool compareDate(const ClassMate &barAmount1, const ClassMate &barAmount2)
{
    if (barAmount1.checkTime_ > barAmount2.checkTime_)
    {
        return true;
    }
    return false;
}

int dirsearch::searchFiles(){
    beginResetModel();
    classMateList_.clear();
    int nFiles(0);
    QDir dir("../Database/DataRetest");
    if (!dir.exists())
        return false;
    dir.setFilter(QDir::Dirs|QDir::Files);//除了目录或文件，其他的过滤掉
    dir.setSorting(QDir::DirsFirst|QDir::Time);//优先显示目录
    list = dir.entryInfoList();//获取文件信息列表
    int i = 0;
    bool bIsDir;
    do{
        QFileInfo fileInfo = list.at(i);
        if(fileInfo.fileName()=="." || fileInfo.fileName()==".." || fileInfo.fileName().contains("="))
        {
            i++;
            continue;
        }
        bIsDir = fileInfo.isDir();
        if (bIsDir)
        {
            //nFiles++;                //对文件属性进行处理
            //fileInfo.size(),fileInfo.fileName(),fileInfo.path()
            //searchFiles(fileInfo.filePath());
        }
        else
        {
            nFiles++;
            ClassMate cm0(nFiles, fileInfo.fileName(), fileInfo.metadataChangeTime().toString("yyyy-MM-dd HH:mm:ss"), fileInfo.absoluteFilePath(),false);
            classMateList_.push_back(cm0);
        }
        i++;
    }
    while(i<list.size());
    //另一种后排序，要处理序号
    //std::sort(classMateList_.begin(),classMateList_.end(),compareDate);
    endResetModel();
    return nFiles;
}


int dirsearch::rowCount(const QModelIndex &parent) const
{
    if (parent.isValid())
        return 0;

    return classMateList_.count();;
}

int dirsearch::columnCount(const QModelIndex &parent) const
{
    if (parent.isValid())
        return 0;

    return 1;
}
QHash<int, QByteArray> dirsearch::roleNames() const
{
    return roleNames_;
}
//! [read]
QVariant dirsearch::data(const QModelIndex &index, int role) const
{
    if (!index.isValid())
        return QVariant();

    ClassMate cm= classMateList_[index.row()];

    if (!index.isValid())
        return QVariant();

    if (role == Qt::TextAlignmentRole)
    {
        return int(Qt::AlignRight | Qt::AlignVCenter);
    }

    switch (role - Qt::UserRole)
    {
    case 0:
        return cm.number_;
    case 1:
        return cm.name_;
    case 2:
        return cm.checkTime_;
    case 3:
        return cm.checked_;
    default:
        break;
    }

    return QVariant();
}
//! [read]
QList<ClassMate>  dirsearch::getData(){
    return classMateList_;
}
//! [write]
bool dirsearch::setData(const QModelIndex &index, const QVariant &value, int role)
{
    //    if (role != CellRole || data(index, role) == value)
    //        return false;

    //    m_currentState[cellIndex({index.column(), index.row()})] = value.toBool();
    if (!index.isValid())
        return false;

    ClassMate cm= classMateList_[index.row()];

    if (!index.isValid())
        return false;

    switch (role - Qt::UserRole)
    {
    case 3:
        cm.checked_=value.toBool();
        break;
    default:
        return false;
    }
    emit dataChanged(index, index, {role});

    return true;
}
//! [write]
bool dirsearch::setProperty(int index, const QVariant &value, QString role){
    //qDebug()<<"dirsearch::setProperty";
    if (index<0 || index>=rowCount())
        return false;

    ClassMate *cm= &classMateList_[index];

    if ("checked" == role)    {
        cm->checked_=value.toBool();
    }
    else {
        return false;
    }

    return true;
}

void dirsearch::checkedAllSame(){
    beginResetModel();
    auto b=classMateList_.begin(),e=classMateList_.end();
    while(b != e){
        b->checked_ = !firstChecked;
        ++b;
    }
    firstChecked=!firstChecked;
    endResetModel();
}
Qt::ItemFlags dirsearch::flags(const QModelIndex &index) const
{
    if (!index.isValid())
        return Qt::NoItemFlags;

    return Qt::ItemIsEditable;
}

int dirsearch::exportExcelEn(){
    qDebug()<<"dirsearch::exportExcelEn";
    exportxlsx *xlsx = new exportxlsx();
    xlsx->setLang(exportxlsx::En);
    connect(xlsx,&exportxlsx::end,this,&dirsearch::excelFinished);
    connect(xlsx,&exportxlsx::idle,this,&dirsearch::excelIdle);
    foreach (auto item, classMateList_) {
        qDebug()<<item.checked_;
        if(item.checked_){
            xlsx->setClassMateList(item);
        }
    }
    pool.start(xlsx);
    qDebug()<<"dirsearch::exportExcelEn end";
    return  0;
}

int dirsearch::exportExcelZh(){
    qDebug()<<"dirsearch::exportExcelZh";
    exportxlsx *xlsx = new exportxlsx();
    xlsx->setLang(exportxlsx::Zh);
    connect(xlsx,&exportxlsx::end,this,&dirsearch::excelFinished);
    connect(xlsx,&exportxlsx::idle,this,&dirsearch::excelIdle);
    foreach (auto item, classMateList_) {
        qDebug()<<item.checked_;
        if(item.checked_){
            xlsx->setClassMateList(item);
        }
    }
    pool.start(xlsx);
    qDebug()<<"dirsearch::exportExcelZh end";
    return 1;
}

int dirsearch::exportExcel(int itype){
    switch (itype) {
    case 1:
    {
        exportRefm *xlsx = new exportRefm();
        connect(xlsx,&exportRefm::end,this,&dirsearch::excelFinished);
        connect(xlsx,&exportRefm::idle,this,&dirsearch::excelIdle);
        foreach (auto item, classMateList_) {
            if(item.checked_){
                xlsx->setClassMateList(item);
            }
        }
        pool.start(xlsx);
        return 1;
    }
    default:break;
    }
    return 0;
}

int dirsearch::deleteRecords(){
    foreach (auto item, classMateList_) {
        if(item.checked_){
            remove(item.fullPath_.toLocal8Bit());
        }
    }
    searchFiles();
    emit excelIdle();
    return 0;
}
